import {
	_decorator,
	Component,
	Node,
	instantiate,
	Prefab,
	SpriteFrame,
	Vec3,
	UITransform,
	view,
	size,
	tween,
} from 'cc';
const { ccclass, property } = _decorator;

@ccclass('GameManager')
export class GameManager extends Component {
	@property({ type: Prefab })
	cardPrefab: Prefab | null = null;

	@property({ type: [SpriteFrame] })
	cardBacks: SpriteFrame[] = [];

	@property({ type: [SpriteFrame] })
	cardFronts: SpriteFrame[] = [];

	@property
	rows: number = 4;

	@property
	cols: number = 4;

	private cards: Node[] = [];
	private flippedCards: Node[] = [];
	private selectedBack: SpriteFrame | null = null;
	private canFlip: boolean = true;

	start() {
		this.initGame();
	}

	initGame() {
		// 清除旧卡牌
		this.cards.forEach((card) => card.destroy());
		this.cards = [];
		this.flippedCards = [];
		this.canFlip = true;

		// 随机选择卡牌背面
		this.selectedBack =
			this.cardBacks[Math.floor(Math.random() * this.cardBacks.length)];

		// 创建卡牌对
		const totalPairs = (this.rows * this.cols) / 2;
		let cardValues: number[] = [];

		for (let i = 0; i < totalPairs; i++) {
			cardValues.push(i, i);
		}

		// 洗牌
		cardValues = this.shuffleArray(cardValues);

		// 计算卡牌大小和间距
		const screenSize = view.getVisibleSize();
		const cardWidth = screenSize.width / (this.cols + 1);
		const cardSize = size(cardWidth, cardWidth);
		const startX = (-(this.cols - 1) * cardWidth) / 2;
		const startY = ((this.rows - 1) * cardWidth) / 2;

		// 创建卡牌网格
		let cardIndex = 0;
		for (let row = 0; row < this.rows; row++) {
			for (let col = 0; col < this.cols; col++) {
				const card = instantiate(this.cardPrefab!);
				this.node.addChild(card);

				const cardScript = card.getComponent('Card') as any;
				cardScript.init(
					this.cardFronts[cardValues[cardIndex]],
					this.selectedBack,
					cardValues[cardIndex],
					this
				);

				card.setPosition(
					startX + col * cardWidth,
					startY - row * cardWidth,
					0
				);

				const uiTransform = card.getComponent(UITransform);
				uiTransform?.setContentSize(cardSize);

				this.cards.push(card);
				cardIndex++;
			}
		}
	}

	shuffleArray(array: any[]) {
		for (let i = array.length - 1; i > 0; i--) {
			const j = Math.floor(Math.random() * (i + 1));
			[array[i], array[j]] = [array[j], array[i]];
		}
		return array;
	}

	onCardClicked(card: Node) {
		if (
			!this.canFlip ||
			this.flippedCards.includes(card) ||
			this.flippedCards.length >= 2
		) {
			return;
		}

		const cardScript = card.getComponent('Card') as any;
		cardScript.flipCard();

		this.flippedCards.push(card);

		if (this.flippedCards.length === 2) {
			this.checkForMatch();
		}
	}

	checkForMatch() {
		const card1 = this.flippedCards[0].getComponent('Card') as any;
		const card2 = this.flippedCards[1].getComponent('Card') as any;

		if (card1.cardValue === card2.cardValue) {
			// 匹配成功
			this.canFlip = false;
			setTimeout(() => {
				this.flippedCards.forEach((card) => {
					const cardScript = card.getComponent('Card') as any;
					cardScript.setMatched();
				});
				this.flippedCards = [];
				this.canFlip = true;
				this.checkGameOver();
			}, 500);
		} else {
			// 不匹配
			this.canFlip = false;
			setTimeout(() => {
				this.flippedCards.forEach((card) => {
					const cardScript = card.getComponent('Card') as any;
					cardScript.flipCard();
				});
				this.flippedCards = [];
				this.canFlip = true;
			}, 1000);
		}
	}

	checkGameOver() {
		const allMatched = this.cards.every((card) => {
			const cardScript = card.getComponent('Card') as any;
			return cardScript.isMatched;
		});

		if (allMatched) {
			setTimeout(() => {
				alert('恭喜你赢了！');
				this.initGame();
			}, 500);
		}
	}
}
